import { Controller, Get, Post, Body, Patch, Param, Delete, HttpException } from '@nestjs/common';
import { UserService } from './user.service';
import { UpdateUserDto } from './dto/update-user.dto';
import { RegisterUserDto } from './dto/register-user-dto';
import { LoginUserDto } from './dto/login-user.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Result } from 'src/utils/result';
import { UserDocument } from './schema/user.schema';
@Controller('user')
@ApiTags('用户')
export class UserController {
  constructor(private readonly userService: UserService) {}
  @Post('/register')
  @ApiOperation({summary:'注册'})
  async register(@Body() registerUserDto:RegisterUserDto):Promise<UserDocument>{
    const hasRegisted=await this.userService.findOneByUsername(registerUserDto.username)
    if(hasRegisted){
      throw new HttpException('用户名已存在',400)
    }else{
      const user=(await this.userService.register(registerUserDto)).toObject()
      delete user['password']
      delete user['_id']
      return user
    }
  }
  @Post('/login')
  @ApiOperation({summary:'登录'})
  async login(@Body() LoginUserDto: LoginUserDto):Promise<UserDocument>{
    const user=await this.userService.findOneByUsernameAndPassword(LoginUserDto.username,LoginUserDto.password);
    if(user){
      const res=user.toObject()
      delete res['password']
      return res
    }else{
      throw new HttpException('用户名或密码错误',400)
    }
  }

  @Post('/update')
  @ApiOperation({summary:'更新'})
  async update(@Body() updateUserDto:UpdateUserDto):Promise<Boolean>{
    return await this.userService.update(updateUserDto)
  }
}
